/**
 * Created by Noir on 1/10/14.
 */
'use strict'
define(['app'], function(app){
    var indexCtrl = function($scope, $location, $http, $route, $log){
        $scope.isFilled = false;
        $scope.pageCount = 0;
        $scope.limit = 5;
        $scope.total = 0;
        $scope.currentPage = 0;

        $http.get('/api/menu').success(function(menu){
            $log.log('get data...');
            $scope.menu = menu;
            $scope.total = menu.length;
            if(($scope.toal % $scope.limit) == 0){
                $scope.pageCount = Math.floor($scope.total / $scope.limit);
            }
            $scope.pageCount = Math.floor($scope.total / $scope.limit) + 1;

            $log.log('Total: ' + $scope.total + "; PageCount: " + $scope.pageCount + "; get floor: " + ($scope.total/$scope.limit));

            if(menu.length > 0){
                $scope.isFilled = true;
            }else{
                $scope.isFilled = false;
            }

            $scope.loadPage(1);
        });

        $scope.loadPage = function(pg){
            $log.log('load page ' + pg);
            // get page
            $http.get('/api/menu/page/'+pg+'/'+$scope.limit).success(function(menu){
                $scope.menu = menu;
            });

            // set current page
            $scope.currentPage = pg;
        }

        $scope.init = function(){
            $log.log("Prepare to init...");
            $http.get('/api/init')
                .success(function(dishes){
                    $log.log('init all.');
                    $route.reload();
                });
        }

        $scope.deleteAll = function(){
            $log.log('Prepare to delete...');
            $http.get('/api/deleteAll')
                .success(function(stt){
                    $log.log('deleted all.');
                    // $route.reload();
                    $scope.menu = [];
                    $scope.isFilled = false;
                });
        }

        $scope.delete = function(id){
            $log.log('id: ' + id);
            $http.delete('/api/menu/' + id).success(function(stt){
                $log.log('deleted.');
                // $route.reload(); // server
                for(var i=0;i<$scope.menu.length;i++){
                    if($scope.menu[i]._id === id){
                        $scope.menu.splice(i, 1);
                    }
                }
            });
        }
    }

    app.register.controller('IndexCtrl',
        ['$scope','$location','$http','$route','$log', indexCtrl ]);
});